package com.tensai;

import com.tensai.core.config.RequestMappingCfg;
import com.tensai.core.interceptor.EncodingInterceptor;
import com.tensai.core.interceptor.SessionInterceptor;
import com.tensai.core.mvc.system.entry.SysResource;
import com.tensai.core.mvc.system.service.ISysResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author Tensai
 * 2018-02-24 16:49
 */
@SpringBootApplication
@ServletComponentScan
@EnableCaching
public class FirstSpringBootApplication extends WebMvcConfigurerAdapter {

    @Autowired
    private RequestMappingCfg requestMappingCfg;

    @Autowired
    private ISysResourceService sysResourceService;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new EncodingInterceptor()).addPathPatterns("/**");
        registry.addInterceptor(new SessionInterceptor()).addPathPatterns("/**").excludePathPatterns("/websocket/**");
//		registry.addInterceptor(new AuthInterceptor()).addPathPatterns("/**");
    }

    public static void main(String[] args) {
        SpringApplication.run(FirstSpringBootApplication.class, args);
    }

    /**
     * 扫描URL，如果数据库中不存在，则保存入数据库
     * 这个注解很重要，可以在每次启动的时候检查是否有URL更新，RequestMappingHandlerMapping只能在controller层用。这里我们放在主类中
     */
//	@PostConstruct
    public void detectHandlerMethods() {
        final RequestMappingHandlerMapping requestMappingHandlerMapping = requestMappingCfg.requestMappingHandlerMapping();
        Map<RequestMappingInfo, HandlerMethod> map = requestMappingHandlerMapping.getHandlerMethods();
        Set<RequestMappingInfo> mappings = map.keySet();
        for (RequestMappingInfo info : mappings) {
            HandlerMethod method = map.get(info);
            String methodstr = method.toString();
            methodstr = methodstr.split("\\(")[0];
            methodstr = methodstr.split(" ")[2];
            int i = methodstr.lastIndexOf(".");
            methodstr = methodstr.substring(0, i);
            String urlparm = info.getPatternsCondition().toString();
            String url = urlparm.substring(1, urlparm.length() - 1);
            List<SysResource> list = sysResourceService.findByResourceString(url);
            if (list == null || list.size() <= 0) {
                int num = (int) (Math.random() * 100 + 1);
                String rand = String.valueOf(num);
                String resourceId = "res" + System.currentTimeMillis() + rand;
                SysResource sysresource = new SysResource();
                sysresource.setResourceString(url);
                sysresource.setRemark("0");
                sysresource.setResourceId(resourceId);
                sysresource.setMethodPath(methodstr);
                sysResourceService.save(sysresource);
            }

        }
    }

    /**
     * 解决单线程任务调度的问题
     *
     * @return taskScheduler
     */
    @Bean
    public TaskScheduler taskScheduler() {
        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
        taskScheduler.setPoolSize(50);
        return taskScheduler;
    }
}

